package com.usesion.service.impl;

import com.usesion.common.constant.Constants;
import com.usesion.common.utils.TreeUtil;
import com.usesion.base.shiro.ShiroUtils;
import com.usesion.entity.Menu;
import com.usesion.entity.Role;
import com.usesion.mapper.MenuMapper;
import com.usesion.mapper.RoleMenuMapper;
import com.usesion.service.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.*;

/**
 * @desc: 菜单业务层处理
 * @author: XT
 */
@Service
public class MenuServiceImpl implements MenuService {

        public static final String PREMISSION_STRING = "perms[\"{0}\"]";

        @Autowired
        private MenuMapper menuMapper;

        @Autowired
        private RoleMenuMapper roleMenuMapper;

        /**
         * 根据用户ID查询菜单
         * @param userId 用户ID
         * @return 菜单列表
         */
        @Override
        public List<Menu> selectMenusByUserId(Integer userId){
            List<Menu> menus = menuMapper.selectMenusByUserId(userId);
            return TreeUtil.getChildPerms(menus, 0);
        }

        /**
         * 查询菜单集合
         * @return 所有菜单信息
         */
        @Override
        public List<Menu> selectMenuAll(){
            return menuMapper.selectMenuAll();
        }

        /**
         * 根据用户ID查询权限
         * @param userId 用户ID
         * @return 权限列表
         */
        @Override
        public Set<String> selectPermsByUserId(Integer userId){
            List<String> perms = menuMapper.selectPermsByUserId(userId);
            Set<String> permsSet = new HashSet<>();
            for (String perm : perms) {
                if (StringUtils.isNotEmpty(perm)) {
                    permsSet.addAll(Arrays.asList(perm.trim().split(",")));
                }
            }
            return permsSet;
        }

        /**
         * 根据角色ID查询菜单
         * @param role 角色对象
         * @return 菜单列表
         */
        @Override
        public List<Map<String, Object>> roleMenuTreeData(Role role) {
            Integer roleId = role.getId();
            List<Map<String, Object>> trees;
            List<Menu> menuList = menuMapper.selectMenuAll();
            if (roleId != null) {
                List<String> roleMenuList = menuMapper.selectMenuTree(roleId);
                trees = getTrees(menuList, true, roleMenuList, true);
            } else {
                trees = getTrees(menuList, false, null, true);
            }
            return trees;
        }

        /**
         * 查询所有菜单
         * @return 菜单列表
         */
        @Override
        public List<Map<String, Object>> menuTreeData(){
            List<Map<String, Object>> trees;
            List<Menu> menuList = menuMapper.selectMenuAll();
            trees = getTrees(menuList, false, null, false);
            return trees;
        }

        /**
         * 查询系统所有权限
         * @return 权限列表
         */
        @Override
        public LinkedHashMap<String, String> selectPermsAll() {
            LinkedHashMap<String, String> section = new LinkedHashMap<>();
            List<Menu> permissions = menuMapper.selectMenuAll();
            if (!permissions.isEmpty()) {
                for (Menu menu : permissions) {
                    section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
                }
            }
            return section;
        }

        /**
         * 对象转菜单树
         * @param menuList 菜单列表
         * @param isCheck 是否需要选中
         * @param roleMenuList 角色已存在菜单列表
         * @param permsFlag 是否需要显示权限标识
         * @return
         */
        public List<Map<String, Object>> getTrees(List<Menu> menuList, boolean isCheck, List<String> roleMenuList, boolean permsFlag) {
            List<Map<String, Object>> trees = new ArrayList<Map<String, Object>>();
            for (Menu menu : menuList) {
                Map<String, Object> deptMap = new HashMap<String, Object>();
                deptMap.put("id", menu.getId());
                deptMap.put("pId", menu.getParentId());
                deptMap.put("name", transMenuName(menu, roleMenuList, permsFlag));
                if (isCheck) {
                    deptMap.put("checked", roleMenuList.contains(menu.getId() + menu.getPerms()));
                } else {
                    deptMap.put("checked", false);
                }
                trees.add(deptMap);
            }
            return trees;
        }

    public String transMenuName(Menu menu, List<String> roleMenuList, boolean permsFlag) {
        StringBuffer sb = new StringBuffer();
        sb.append(menu.getName());
        if (permsFlag) {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
        }
        return sb.toString();
    }

    /**
     * 删除菜单管理信息
     * @param id 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Integer id) {
        ShiroUtils.clearCachedAuthorizationInfo();
        return menuMapper.deleteMenuById(id);
    }

    /**
     * 根据菜单ID查询信息
     * @param id 菜单ID
     * @return 菜单信息
     */
    @Override
    public Menu selectMenuById(Integer id) {
        return menuMapper.selectMenuById(id);
    }

    /**
     * 查询子菜单数量
     * @param parentId 父菜单ID
     * @return 结果
     */
    @Override
    public int selectCountMenuByParentId(Integer parentId) {
        return menuMapper.selectCountMenuByParentId(parentId);
    }

    /**
     * 查询菜单使用数量
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int selectCountRoleMenuByMenuId(Integer menuId) {
        return roleMenuMapper.selectCountRoleMenuByMenuId(menuId);
    }

    /**
     * 保存菜单信息
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int saveMenu(Menu menu) {
        Integer menuId = menu.getId();
        if (menuId != null) {
            menu.setUpdateBy(ShiroUtils.getUserName());
            ShiroUtils.clearCachedAuthorizationInfo();
            return menuMapper.updateMenu(menu);
        } else {
            menu.setCreateBy(ShiroUtils.getUserName());
            ShiroUtils.clearCachedAuthorizationInfo();
            return menuMapper.insertMenu(menu);
        }
    }

    /**
     * 校验菜单名称是否唯一
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(Menu menu) {
        if (menu.getId() == null) {
            menu.setId(-1);
        }
        Integer menuId = menu.getId();
        Menu info = menuMapper.checknameUnique(menu.getName());
        if (info != null && info.getId() != null
                && !info.getId().equals(menuId)) {
            return Constants.MENU_NAME_NOT_UNIQUE;
        }
        return Constants.MENU_NAME_UNIQUE;
    }
}
